import React, { useState, useMemo } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Modal } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { getWeekRange, getWeekDates } from '../utils/dateUtils';
import usePlanStore from '../store/planStore';
import { usePlans } from '../hooks/usePlans';
import { createCommonStyles } from '../styles/commonStyles';
import { useTheme } from '../hooks/useTheme';
import Button from '../components/common/Button';
import Input from '../components/common/Input';
import ProgressBar from '../components/common/ProgressBar';
import SubPlanItem from '../components/plan/SubPlanItem';

const WeeklyScreen = () => {
  const { 
    weeklyPlans, 
    plans,
    settings, 
    addWeeklyPlan, 
    updateWeeklyPlan, 
    deleteWeeklyPlan,
    addWeeklySubTask,
    updateWeeklySubTask,
    toggleWeeklySubTask,
    deleteWeeklySubTask,
  } = usePlanStore();
  const { getPlansByDate } = usePlans();
  const { theme } = useTheme();
  const dynamicStyles = createCommonStyles(theme);
  const weekRange = getWeekRange(new Date(), settings.weekStartDay);
  const weekDates = getWeekDates(new Date(), settings.weekStartDay);
  
  // 格式化日期为 MM.DD 格式
  const formatDateShort = (dateStr) => {
    const [year, month, day] = dateStr.split('-');
    return `${month}.${day}`;
  };
  
  // 获取本周的所有日计划，按日期分组
  const weeklyDailyPlans = useMemo(() => {
    const grouped = {};
    weekDates.forEach(({ date, dayName }) => {
      const dayPlans = getPlansByDate(date);
      if (dayPlans.length > 0) {
        grouped[date] = {
          date,
          dayName,
          plans: dayPlans,
        };
      }
    });
    return grouped;
  }, [weekDates, getPlansByDate, plans]);
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showTaskModal, setShowTaskModal] = useState(false);
  const [editingPlan, setEditingPlan] = useState(null);
  const [editingTask, setEditingTask] = useState(null);
  const [currentPlanId, setCurrentPlanId] = useState(null);
  const [planTitle, setPlanTitle] = useState('');
  const [planDescription, setPlanDescription] = useState('');
  const [taskTitle, setTaskTitle] = useState('');
  const [taskDescription, setTaskDescription] = useState('');

  const handleAddPlan = () => {
    if (planTitle.trim()) {
      addWeeklyPlan({
        weekStart: weekRange.weekStart,
        weekEnd: weekRange.weekEnd,
        title: planTitle,
        description: planDescription,
        tasks: [],
      });
      setPlanTitle('');
      setPlanDescription('');
      setShowAddModal(false);
    }
  };

  const handleEditPlan = (plan) => {
    setEditingPlan(plan);
    setPlanTitle(plan.title || '');
    setPlanDescription(plan.description || '');
    setShowEditModal(true);
  };

  const handleUpdatePlan = () => {
    if (planTitle.trim() && editingPlan) {
      updateWeeklyPlan(editingPlan.id, {
        title: planTitle,
        description: planDescription,
      });
      setPlanTitle('');
      setPlanDescription('');
      setEditingPlan(null);
      setShowEditModal(false);
    }
  };

  const handleDeletePlan = (planId) => {
    deleteWeeklyPlan(planId);
  };

  const handleAddTask = (planId) => {
    setCurrentPlanId(planId);
    setTaskTitle('');
    setTaskDescription('');
    setEditingTask(null);
    setShowTaskModal(true);
  };

  const handleEditTask = (planId, task) => {
    setCurrentPlanId(planId);
    setEditingTask(task);
    setTaskTitle(task.title);
    setTaskDescription(task.description || '');
    setShowTaskModal(true);
  };

  const handleSaveTask = () => {
    if (taskTitle.trim() && currentPlanId) {
      if (editingTask) {
        updateWeeklySubTask(currentPlanId, editingTask.id, {
          title: taskTitle,
          description: taskDescription,
        });
      } else {
        addWeeklySubTask(currentPlanId, {
          title: taskTitle,
          description: taskDescription,
        });
      }
      setTaskTitle('');
      setTaskDescription('');
      setEditingTask(null);
      setCurrentPlanId(null);
      setShowTaskModal(false);
    }
  };

  const handleToggleTask = (planId, taskId) => {
    toggleWeeklySubTask(planId, taskId);
  };

  const handleDeleteTask = (planId, taskId) => {
    deleteWeeklySubTask(planId, taskId);
  };

  const closeModals = () => {
    setShowAddModal(false);
    setShowEditModal(false);
    setShowTaskModal(false);
    setEditingPlan(null);
    setEditingTask(null);
    setCurrentPlanId(null);
    setPlanTitle('');
    setPlanDescription('');
    setTaskTitle('');
    setTaskDescription('');
  };

  return (
    <SafeAreaView style={[dynamicStyles.container, { backgroundColor: theme.colors.background }]} edges={['top']}>
      <ScrollView style={[dynamicStyles.content, { backgroundColor: theme.colors.background }]}>
        <View style={styles.header}>
          <Text style={[styles.weekText, { color: theme.colors.text }]}>
            {formatDateShort(weekRange.weekStart)}-{formatDateShort(weekRange.weekEnd)}
          </Text>
          <Text style={[styles.subtitle, { color: theme.colors.textSecondary }]}>本周计划</Text>
        </View>

        {weeklyPlans.length === 0 ? (
          <View style={styles.emptyContainer}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>本周还没有计划</Text>
            <Text style={[styles.emptyHint, { color: theme.colors.textSecondary }]}>点击下方按钮添加计划</Text>
          </View>
        ) : (
          <View>
            {weeklyPlans.map((plan) => (
              <View key={plan.id} style={[dynamicStyles.card, { backgroundColor: theme.colors.card }]}>
                {/* 计划头部 */}
                <View style={styles.planHeader}>
                  <View style={styles.planTitleContainer}>
                    <Text style={[styles.planTitle, { color: theme.colors.text }]}>{plan.title}</Text>
                    {plan.description && (
                      <Text style={[styles.planDescription, { color: theme.colors.textSecondary }]}>{plan.description}</Text>
                    )}
                  </View>
                  <View style={styles.planActions}>
                    <TouchableOpacity 
                      style={[styles.actionButton, { backgroundColor: theme.colors.surface }]}
                      onPress={() => handleEditPlan(plan)}
                    >
                      <Text style={[styles.actionText, { color: theme.colors.primary }]}>编辑</Text>
                    </TouchableOpacity>
                    <TouchableOpacity 
                      style={[styles.actionButton, styles.deleteButton, { backgroundColor: theme.colors.error + '20' }]}
                      onPress={() => handleDeletePlan(plan.id)}
                    >
                      <Text style={[styles.actionText, styles.deleteText, { color: theme.colors.error }]}>删除</Text>
                    </TouchableOpacity>
                  </View>
                </View>

                {/* 进度条 */}
                <View style={styles.progressContainer}>
                  <ProgressBar progress={plan.completionRate || 0} height={10} />
                  <Text style={[styles.progressText, { color: theme.colors.textSecondary }]}>
                    {plan.tasks?.length || 0} 个任务，完成 {plan.tasks?.filter(t => t.status === 'completed').length || 0} 个
                  </Text>
                </View>

                {/* 子任务列表 */}
                <View style={styles.tasksContainer}>
                  {plan.tasks && plan.tasks.length > 0 ? (
                    plan.tasks.map((task) => (
                      <SubPlanItem
                        key={task.id}
                        subPlan={task}
                        onToggle={() => handleToggleTask(plan.id, task.id)}
                        onEdit={() => handleEditTask(plan.id, task)}
                        onDelete={() => handleDeleteTask(plan.id, task.id)}
                      />
                    ))
                  ) : (
                    <Text style={[styles.noTasksText, { color: theme.colors.textSecondary }]}>暂无子任务</Text>
                  )}
                </View>

                {/* 添加子任务按钮 */}
                <TouchableOpacity
                  style={[styles.addTaskButton, { backgroundColor: theme.colors.surface }]}
                  onPress={() => handleAddTask(plan.id)}
                >
                  <Text style={[styles.addTaskText, { color: theme.colors.primary }]}>+ 添加子任务</Text>
                </TouchableOpacity>
              </View>
            ))}
          </View>
        )}

        {/* 本周日计划 */}
        {Object.keys(weeklyDailyPlans).length > 0 && (
          <View style={styles.dailyPlansSection}>
            <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>本周日计划</Text>
            {weekDates.map(({ date, dayName }) => {
              const dayPlans = weeklyDailyPlans[date];
              if (!dayPlans || dayPlans.plans.length === 0) {
                return null;
              }
              
              return (
                <View key={date} style={styles.dayPlanGroup}>
                  <Text style={[styles.dayHeader, { color: theme.colors.text }]}>
                    {dayName}
                  </Text>
                  {dayPlans.plans.map((plan, index) => (
                    <View key={plan.id} style={styles.planListItem}>
                      <Text style={[styles.planListNumber, { color: theme.colors.textSecondary }]}>
                        {index + 1}.
                      </Text>
                      <View style={styles.planListContent}>
                        <Text style={[
                          styles.planListTitle,
                          { color: theme.colors.text },
                          plan.status === 'completed' && [styles.completedText, { color: theme.colors.textSecondary }]
                        ]}>
                          {plan.title}
                        </Text>
                        {plan.description && (
                          <Text style={[
                            styles.planListDescription,
                            { color: theme.colors.textSecondary }
                          ]}>
                            {plan.description}
                          </Text>
                        )}
                      </View>
                    </View>
                  ))}
                </View>
              );
            })}
          </View>
        )}
      </ScrollView>

      {/* 添加计划按钮 */}
      <View style={styles.fabContainer}>
        <TouchableOpacity
          style={[styles.fab, { backgroundColor: theme.colors.primary }]}
          onPress={() => setShowAddModal(true)}
          activeOpacity={0.7}
        >
          <Text style={styles.fabText}>+</Text>
        </TouchableOpacity>
      </View>

      {/* 添加/编辑计划模态框 */}
      <Modal
        visible={showAddModal || showEditModal}
        transparent={true}
        animationType="slide"
        onRequestClose={closeModals}
      >
        <View style={[styles.modalOverlay, { backgroundColor: 'rgba(0, 0, 0, 0.5)' }]}>
          <View style={[styles.modalContent, { backgroundColor: theme.colors.card }]}>
            <Text style={[styles.modalTitle, { color: theme.colors.text }]}>
              {showEditModal ? '编辑周计划' : '添加周计划'}
            </Text>
            
            <Input
              label="计划标题"
              value={planTitle}
              onChangeText={setPlanTitle}
              placeholder="请输入计划标题"
            />
            
            <Input
              label="计划描述（可选）"
              value={planDescription}
              onChangeText={setPlanDescription}
              placeholder="请输入计划描述"
              multiline
            />

            <View style={styles.modalButtons}>
              <Button
                title="取消"
                variant="secondary"
                onPress={closeModals}
                style={styles.modalButton}
              />
              <Button
                title={showEditModal ? '保存' : '添加'}
                onPress={showEditModal ? handleUpdatePlan : handleAddPlan}
                style={styles.modalButton}
              />
            </View>
          </View>
        </View>
      </Modal>

      {/* 添加/编辑子任务模态框 */}
      <Modal
        visible={showTaskModal}
        transparent={true}
        animationType="slide"
        onRequestClose={closeModals}
      >
        <View style={[styles.modalOverlay, { backgroundColor: 'rgba(0, 0, 0, 0.5)' }]}>
          <View style={[styles.modalContent, { backgroundColor: theme.colors.card }]}>
            <Text style={[styles.modalTitle, { color: theme.colors.text }]}>
              {editingTask ? '编辑子任务' : '添加子任务'}
            </Text>
            
            <Input
              label="任务标题"
              value={taskTitle}
              onChangeText={setTaskTitle}
              placeholder="请输入任务标题"
            />
            
            <Input
              label="任务描述（可选）"
              value={taskDescription}
              onChangeText={setTaskDescription}
              placeholder="请输入任务描述"
              multiline
            />

            <View style={styles.modalButtons}>
              <Button
                title="取消"
                variant="secondary"
                onPress={closeModals}
                style={styles.modalButton}
              />
              <Button
                title={editingTask ? '保存' : '添加'}
                onPress={handleSaveTask}
                style={styles.modalButton}
              />
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  header: {
    marginBottom: 24,
  },
  weekText: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 18,
  },
  emptyHint: {
    fontSize: 14,
    marginTop: 8,
  },
  planHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 16,
  },
  planTitleContainer: {
    flex: 1,
  },
  planTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 4,
  },
  planDescription: {
    fontSize: 14,
  },
  planActions: {
    flexDirection: 'row',
    gap: 8,
  },
  actionButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 6,
  },
  deleteButton: {},
  actionText: {
    fontSize: 12,
    fontWeight: '500',
  },
  deleteText: {},
  progressContainer: {
    marginBottom: 16,
  },
  progressText: {
    fontSize: 12,
    marginTop: 8,
  },
  tasksContainer: {
    marginBottom: 12,
  },
  noTasksText: {
    fontSize: 14,
    fontStyle: 'italic',
    marginLeft: 32,
    marginBottom: 8,
  },
  addTaskButton: {
    paddingVertical: 10,
    paddingHorizontal: 12,
    borderRadius: 6,
    alignItems: 'center',
  },
  addTaskText: {
    fontSize: 14,
    fontWeight: '500',
  },
  fabContainer: {
    position: 'absolute',
    bottom: 20,
    right: 20,
    zIndex: 1000,
  },
  fab: {
    width: 48,
    height: 48,
    borderRadius: 24,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  fabText: {
    fontSize: 28,
    color: '#FFFFFF',
    fontWeight: '300',
    lineHeight: 28,
  },
  modalOverlay: {
    flex: 1,
    justifyContent: 'flex-end',
  },
  modalContent: {
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 24,
    paddingBottom: 40,
    maxHeight: '80%',
  },
  modalTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 24,
  },
  modalButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 24,
    gap: 12,
  },
  modalButton: {
    flex: 1,
  },
  dailyPlansSection: {
    marginTop: 32,
  },
  sectionTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 16,
  },
  dayPlanGroup: {
    marginBottom: 20,
  },
  dayHeader: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 12,
    paddingLeft: 4,
  },
  planListItem: {
    flexDirection: 'row',
    marginBottom: 12,
    paddingLeft: 4,
  },
  planListNumber: {
    fontSize: 14,
    fontWeight: '600',
    marginRight: 8,
    minWidth: 24,
  },
  planListContent: {
    flex: 1,
  },
  planListTitle: {
    fontSize: 14,
    fontWeight: '500',
    marginBottom: 4,
  },
  planListDescription: {
    fontSize: 12,
    marginTop: 2,
  },
  completedText: {
    textDecorationLine: 'line-through',
  },
});

export default WeeklyScreen;
